package com.elegantmall.service;

import com.elegantmall.dao.CartDao;

import com.elegantmall.dao.GoodsDao;
import com.elegantmall.pojo.CartPojo;

import com.elegantmall.pojo.GoodsPojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
    @Transactional(rollbackFor = Exception.class)
    public class CartServiceImpl {


        @Autowired
        private CartDao cartDao;


        public List<CartPojo> getCartList(String userName) {

            List<CartPojo> cartList = cartDao.selectByUserName(userName);
            return cartList;

        }


    public String addToCart(String userName, String goodsId, Integer number, Double price) {
        CartPojo cartItem = new CartPojo();
        cartItem.setUserName(userName);
        cartItem.setGoodsId(goodsId);
        cartItem.setNumber(number != null ? number : 1); // 默认数量1
        cartItem.setPrice(price);

        cartDao.customInsert(cartItem);
        return STR."商品 \{goodsId} 已添加到购物车";
    }

    public String increaseNumber(String goodsId) {

        int updated = cartDao.increaseByOne(goodsId);

        return updated > 0 ? "数量+1成功" : "操作失败（商品可能不存在）";
    }

    public String decreaseNumber(String goodsId) {
        // 直接通过goodsId删除（需确保goods_id全局唯一）
        int affected = cartDao.decreaseByGoodsId(goodsId);

        if (affected > 0) {
            return "数量-1成功";
        } else {
            // 尝试删除数量≤1的记录
            int deleted = cartDao.deleteWhenLteOne(goodsId);
            return deleted > 0 ? "已移除商品" : "操作失败";
        }
    }

    public String deleteCartItem(String userName, String goodsId) {

        int affected = cartDao.directDelete(userName, goodsId);
        return affected > 0 ? "删除成功" : "商品不存在";
    }

    public String updateQuantity(CartPojo cart) {
        // 参数校验...

        int affected = cartDao.directUpdate(
                cart.getUserName(),
                cart.getGoodsId(),
                cart.getNumber()
        );

        return affected > 0 ? "更新成功" : "商品不存在或无权操作";
    }

}